/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package netoppiggy_interface;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;

/**
 *
 * @author
 * Dai
 */
public class FormChat extends javax.swing.JInternalFrame {

    public String _labelName = "";
    public String _nameSocket;
    final int PORT = 1102;
    public Socket _socketClient;
    PrintWriter _out;
    private ObjectOutputStream outStream;

    /*public JTextArea getJTextArea(){
     return this.txtConvasation;
     }
     public JTextField getJTextFieldND(){
     return this.txtNoiDung;
     }*/
    public void appendText(String text) {

        this.txtConvasation.append(text);
    }

    public void sendMessage(String msg) {
        if (!msg.isEmpty()) {
            this._out.println(msg);
            this._out.flush();
        }
    }

    /**
     * Creates
     * new
     * form
     * FormChat
     */
    public FormChat() {
        initComponents();
    }

    public FormChat(Socket Client, String socketName) {
        initComponents();

        this._socketClient = Client;
        this._nameSocket = socketName;
        try {
            _out = new PrintWriter(new OutputStreamWriter(Client.getOutputStream()));
        } catch (IOException ex) {
            Logger.getLogger(FormChat.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * This
     * method
     * is
     * called
     * from
     * within
     * the
     * constructor
     * to
     * initialize
     * the
     * form.
     * WARNING:
     * Do
     * NOT
     * modify
     * this
     * code.
     * The
     * content
     * of
     * this
     * method
     * is
     * always
     * regenerated
     * by
     * the
     * Form
     * Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        txtConvasation = new javax.swing.JTextArea();
        btnSend = new javax.swing.JButton();
        txtNoiDung = new javax.swing.JTextField();
        btnChooseFile = new javax.swing.JButton();

        setBorder(null);
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setDoubleBuffered(true);

        txtConvasation.setColumns(20);
        txtConvasation.setRows(5);
        jScrollPane1.setViewportView(txtConvasation);

        btnSend.setText("Send");
        btnSend.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSendActionPerformed(evt);
            }
        });

        txtNoiDung.setText("jTextField1");

        btnChooseFile.setText("Choose File");
        btnChooseFile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnChooseFileActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(49, 49, 49)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 484, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(txtNoiDung, javax.swing.GroupLayout.PREFERRED_SIZE, 398, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(btnSend)))
                .addContainerGap(48, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(btnChooseFile)
                .addGap(153, 153, 153))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btnChooseFile)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 23, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 273, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(32, 32, 32)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtNoiDung, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnSend))
                .addGap(28, 28, 28))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnSendActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSendActionPerformed
        // TODO add your handling code here:
        this.sendMessage(this._nameSocket + ": " + this.txtNoiDung.getText());
        this.appendText("\n" + this._nameSocket + ": " + this.txtNoiDung.getText());
    }//GEN-LAST:event_btnSendActionPerformed

    public void sendFile(File file) throws IOException, ClassNotFoundException {
        try {
            byte[] buf = new byte[1024];
            OutputStream os = this._socketClient.getOutputStream();
            BufferedOutputStream out = new BufferedOutputStream(os, 1024);
            FileInputStream in = new FileInputStream(file);
            int i = 0;
            int bytecount = 1024;
            while ((i = in.read(buf, 0, 1024)) != -1) {
                bytecount = bytecount + 1024;
                out.write(buf, 0, i);
                out.flush();
            }
            this._socketClient.shutdownOutput();
            //System.out.println("Bytes Sent :" + bytecount);

            //ObjectInputStream ois = new ObjectInputStream(this._socketClient.getInputStream());
            //ois.skip(Long.MAX_VALUE);
            //String confirmation = (String) ois.readObject();
            //System.out.println("from server : " + confirmation);

            out.close();
            in.close();
        } catch (IOException ex) {
            Logger.getLogger(FormChat.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void receiveFile(File file) throws IOException {
        try {
            byte[] b = new byte[1024];
            int len = 0;
            int bytcount = 1024;
            FileOutputStream inFile = new FileOutputStream(file);
            InputStream is = this._socketClient.getInputStream();
            BufferedInputStream in2 = new BufferedInputStream(is, 1024);
            while ((len = in2.read(b, 0, 1024)) != -1) {
                bytcount = bytcount + 1024;
                inFile.write(b, 0, len);
            }
            System.out.println("Bytes Writen : " + bytcount);

            // Sending the response back to the client.
            ObjectOutputStream oos = new ObjectOutputStream(this._socketClient.getOutputStream());
            oos.flush();
            oos.writeObject("ok");
            System.out.println("Message sent to the client is " + "ok");

            in2.close();
            inFile.close();
        } catch (IOException ex) {
            Logger.getLogger(FormChat.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void btnChooseFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnChooseFileActionPerformed
        // TODO add your handling code here:
        JFileChooser choose = new JFileChooser();
        int returnVal = choose.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            String line = null;
            int line1 = 0;
            File file = choose.getSelectedFile();
            try {
                String name = file.getName();
                //this.sendMessage("sendfile-" + file.getName());
                this.sendMessage("sendfile--" + file.getName());
                this.sendFile(file);
                /*try {
                    FileInputStream bufferedFileReader = new FileInputStream(file.getPath());
                    DataOutputStream streamWriter = new DataOutputStream(_socketClient.getOutputStream());
                    PrintWriter outTextStream = new PrintWriter(_socketClient.getOutputStream(), true);
                    BufferedReader in = new BufferedReader(new InputStreamReader(_socketClient.getInputStream()));

                    streamWriter.flush();

                    byte[] buff = new byte[1024];
                    while ((line1 = bufferedFileReader.read(buff, 0, 1024)) > -1) {
                        streamWriter.write(buff);
                        //System.out.println(buff);
                    }
                    streamWriter.flush();
                } catch (FileNotFoundException ex) {
                    Logger.getLogger(FormChat.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IOException ex) {
                    Logger.getLogger(FormChat.class.getName()).log(Level.SEVERE, null, ex);
                }*/



                //This is where a real application would save the file.
            } catch (IOException ex) {
                Logger.getLogger(FormChat.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(FormChat.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
        //choose.setVisible(true);

    }//GEN-LAST:event_btnChooseFileActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnChooseFile;
    private javax.swing.JButton btnSend;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea txtConvasation;
    private javax.swing.JTextField txtNoiDung;
    // End of variables declaration//GEN-END:variables
}
